<!-- 给大屏使用 -->
<template>
  <div class="mapview-pannel1">
    <el-alert
      title="请先选择合适的房屋类型,地势类型"
      type="error"
      effect="dark"
    >
    </el-alert>
    <div class="top">
      <el-row class="rowclass">
        <el-col :span="6">
          房屋类型：
          <el-select
            v-model="houseValue"
            placeholder="请选择"
            @change="getHouseType"
          >
            <el-option
              v-for="item in houseType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          地势类型：
          <el-select
            v-model="warnValue1"
            placeholder="请选择"
            @change="getDiShiType"
          >
            <el-option
              v-for="item in warnType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" size="small" plain @click="submitHouseList"
            >提交所选房屋</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button type="danger" size="small" plain @click="clearMapView()"
            >清空所选房屋</el-button
          >
        </el-col>
      </el-row>
    </div>
    <div id="mapview2"></div>
    <div id="clearDiv" class="clear"></div>
    <map-info
      :showInfo="showInfo"
      :datas="selectData"
      :fwlb="fwlb"
      :terrainType="warnValue1"
      @closeHouse="closeInfo"
    />
  </div>
</template>

<script>
import { loadModules } from 'esri-loader'
import mapInfo from './mapInfo.vue'

export default {
  name: 'Mapview',
  props: ['lat', 'lon'],
  components: { mapInfo },
  data() {
    return {
      view1: {},
      map1: {},
      showInfo: false,
      datas: [],
      type: '', //判断下当前类型，加载不同的接口
      // lat: 0.0,
      // lon: 0.0,
      parksLayer: {},
      selectData: [], //框选中的房屋集合
      houseType: [
        {
          value: '1',
          label: '城镇住宅',
        },
        {
          value: '2',
          label: '城镇非住宅',
        },
        {
          value: '3',
          label: '农村独立住宅',
        },
        {
          value: '4',
          label: '农村非独立住宅',
        },
        {
          value: '5',
          label: '农村集合住宅',
        },
      ], //房屋类型
      houseValue: '', //房屋类型值
      warnType: [
        {
          value: '1',
          label: '主城区',
        },
        {
          value: '2',
          label: '低洼',
        },
        {
          value: '3',
          label: '坡地',
        },

        {
          value: '4',
          label: '地震带',
        },
        // {
        //   value: '5',
        //   label: '灾前台风预警',
        // },
        // {
        //   value: '6',
        //   label: '灾前雪灾预警',
        // },
        // {
        //   value: '7',
        //   label: '灾前洪涝预警',
        // },
        // {
        //   value: '8',
        //   label: '灾后台风预警',
        // },
        // {
        //   value: '9',
        //   label: '灾后洪涝预警',
        // },
        // {
        //   value: '10',
        //   label: '灾后地震预警',
        // },
      ], //灾前预警类型
      warnValue1: '', //预警类型值
      urls: '',
      selectArea: [], //选中的区域范围
      fwlb: '',
      parksLayer2: {},
    }
  },
  watch: {
    lat: {
      handler(newVal) {
        this.lat = newVal
      },
      immediate: true,
    },
    lon: {
      handler(newVal) {
        this.lon = newVal
      },
      immediate: true,
    },
  },
  methods: {
    getHouseType(e) {
      console.log('12312312', e)
      this.urls = ''
      // 城镇住宅-city_on_house，城镇非住宅-city_non_house，
      //农村独立住宅-village_dl_house，农村集合用房-village_jh_house，农村非住宅-village_non_house
      // if (e == 1) {
      //   this.fwlb = 'city_on_house'
      //   //城镇住宅
      //   this.urls =
      //     'https://gis.sdhuan.cn/arcgis/rest/services/370800cityon/MapServer'
      // } else if (e == 2) {
      //   this.fwlb = 'city_non_house'
      //   //城镇非住宅
      //   this.urls =
      //     'https://gis.sdhuan.cn/arcgis/rest/services/370800citynon/MapServer'
      // } else if (e == 3) {
      //   this.fwlb = 'village_dl_house'
      //   //农村独立住宅
      //   this.urls =
      //     'https://gis.sdhuan.cn/arcgis/rest/services/370800villagedl/MapServer'
      // } else if (e == 4) {
      //   this.fwlb = 'village_non_house'
      //   //农村非独立住宅
      //   this.urls =
      //     'https://gis.sdhuan.cn/arcgis/rest/services/370800villagenon/MapServer'
      // } else if (e == 5) {
      //   this.fwlb = 'village_jh_house'
      //   //农村集合住宅
      //   this.urls =
      //     'https://gis.sdhuan.cn/arcgis/rest/services/370800villagejh/MapServer'
      // } else if (e == 6) {
      //   this.fwlb = 'city_on_house'
      //   //城镇住宅
      //   this.urls =
      //     'https://gis.sdhuan.cn/arcgis/rest/services/370800cityon/MapServer'
      // } else {
      //   this.fwlb = 'city_on_house'
      //   //城镇住宅
      //   this.urls =
      //     'https://gis.sdhuan.cn/arcgis/rest/services/370800cityon/MapServer'
      // }
      if (e == 1) {
        this.fwlb = 'city_on_house'
        //城镇住宅
        this.urls =
          'https://gis.sdhuan.cn/arcgis/rest/services/2022370800cityon/MapServer'
        // 'https://gis.sdhuan.cn/arcgis/rest/services/370800cityon/MapServer'
      } else if (e == 2) {
        this.fwlb = 'city_non_house'
        //城镇非住宅
        this.urls =
          'https://gis.sdhuan.cn/arcgis/rest/services/2022370800citynon/MapServer'
        // 'https://gis.sdhuan.cn/arcgis/rest/services/370800citynon/MapServer'
      } else if (e == 3) {
        this.fwlb = 'village_dl_house'
        //农村独立住宅
        this.urls =
          'https://gis.sdhuan.cn/arcgis/rest/services/2022370800villagedlfz/MapServer'
        // 'https://gis.sdhuan.cn/arcgis/rest/services/370800villagedl/MapServer'
      } else if (e == 4) {
        this.fwlb = 'village_non_house'
        //农村非独立住宅
        this.urls =
          'https://gis.sdhuan.cn/arcgis/rest/services/2022370800villagenon/MapServer'
        // 'https://gis.sdhuan.cn/arcgis/rest/services/370800villagenon/MapServer'
      } else if (e == 5) {
        this.fwlb = 'village_jh_house'
        //农村集合住宅
        this.urls =
          'https://gis.sdhuan.cn/arcgis/rest/services/2022370800villagejh/MapServer'
        // 'https://gis.sdhuan.cn/arcgis/rest/services/370800villagejh/MapServer'
      } else if (e == 6) {
        this.fwlb = 'city_on_house'
        //城镇住宅
        this.urls =
          'https://gis.sdhuan.cn/arcgis/rest/services/2022370800cityon/MapServer'
      } else {
        this.fwlb = 'city_on_house'
        //城镇住宅
        this.urls =
          'https://gis.sdhuan.cn/arcgis/rest/services/2022370800cityon/MapServer'
      }
      // if (this.warnValue1) {
      this._createMapView()
      // }
    },
    getDiShiType() {
      // this._createMapView() 
      // this.getOldSelect()
    },
    //创建地图
    _createMapView: function () {
      const _self = this //定义一个_self防止后续操作中this丢失
      const option = {
        url: 'https://js.arcgis.com/4.18/init.js',
        css: 'https://js.arcgis.com/4.18/esri/themes/light/main.css',
      }

      //通过loadModules来做衔接
      loadModules(
        [
          'esri/Map',
          'esri/views/MapView',
          'esri/config',
          'esri/widgets/BasemapToggle',
          'esri/widgets/BasemapGallery',
          'esri/Graphic',
          'esri/widgets/Sketch',
          'esri/layers/GraphicsLayer',
          'esri/layers/FeatureLayer',
        ],
        option
      )
        .then(
          ([
            Map,
            MapView,
            esriConfig,
            BasemapToggle,
            BasemapGallery,
            Graphic,
            Sketch,
            GraphicsLayer,
            FeatureLayer,
          ]) => {
            esriConfig.apiKey =
              'AAPKdf2979e7d74a47c89d398c8715dc6272d1rJcplaaCYMDoyFMXavlgP41dIAEJ1AtiD_HaH4zbxgkpbazqf9C9E3pveLBGsG'
            //业务代码在此处编写
            const map = new Map({
              //实例化地图
              basemap: 'satellite',
            })
            this.map1 = map

            const view = new MapView({
              //实例化地图视图
              container: 'mapview2',
              map: map,
              zoom: 18,
              center: [this.lon, this.lat],
            })
            this.view1 = view

            const graphicsLayer = new GraphicsLayer()
            map.add(graphicsLayer)

            const sketch = new Sketch({
              layer: graphicsLayer,
              view: view,
              creationMode: 'update', // Auto-select
            })

            view.ui.add(sketch, 'top-right')

            sketch.on('update', (event) => {
              if (event.state === 'start') {
                this.queryFeaturelayer2(this.view1, event.graphics[0].geometry)
              }
              if (event.state === 'complete') {
                graphicsLayer.remove(event.graphics[0]) // Clear the graphic when a user clicks off of it or sketches new one
              }
              // Change
              if (
                event.toolEventInfo &&
                (event.toolEventInfo.type === 'scale-stop' ||
                  event.toolEventInfo.type === 'reshape-stop' ||
                  event.toolEventInfo.type === 'move-stop')
              ) {
                this.queryFeaturelayer2(this.view1, event.graphics[0].geometry)
              }
            })

            this.parksLayer = new FeatureLayer({
              url: this.urls,
            })
            this.map1.add(this.parksLayer, 0)
            if(this.fwlb=='village_dl_house'){
              this.parksLayer2 = new FeatureLayer({
                url: 'https://gis.sdhuan.cn/arcgis/rest/services/2022370800villagefz/MapServer',
              })
              this.map1.add(this.parksLayer2, 0)
            }
          }
        )
        .catch((err) => {
           _self.$message('地图创建失败，' + err)
        })
    },

    //多条件查询
    queryFeaturelayer2(view, geometry) {
      const parcelQuery = {
        spatialRelationship: 'intersects', // Relationship operation to apply
        geometry: geometry, // The sketch feature geometry
        outFields: ['*'], // Attributes to return
        returnGeometry: true,
      }

      this.parksLayer
        .queryFeatures(parcelQuery)
        .then((results) => {
          console.log('Feature count: ' + results.features[0])
          // this.selectData.push(results)
          if (results.features.length > 0) {
            this.openInfo(results.features)
          }
          this.displayResults2(view, results.features, '1')
        })
        .catch((error) => {
          console.log(error)
        })
    },
    //开启弹窗
    openInfo(features) {
      features.forEach((item) => {
        if (
          JSON.stringify(this.selectData).indexOf(item.attributes.fwbh) == -1
        ) {
          this.selectData.push(item.attributes)
        }
        if (
          JSON.stringify(this.selectArea).indexOf(item.attributes.fwbh) == -1
        ) {
          this.selectArea.push(item)
        }
      })
    },
    //关闭弹窗
    closeInfo(val) {
      this.clearMapView()
      this.showInfo = val
      this.datas = []
    },

    // Show features (graphics)
    displayResults2(view, features, type) {
      // Create a blue polygon
      var symbol = {}
      var popupTemplate = {}
      console.log(features)
      if (type === '1') {
        symbol = {
          type: 'simple-fill',
          color: [20, 130, 200, 0.5],
          outline: {
            color: 'white',
            width: 0.5,
          },
        }
        popupTemplate = {
          title: '房屋编号：{fwbh}',
          content: '地址：{address}',
        }
      } else {
        symbol = {
          type: 'simple-fill',
          color: [20, 130, 200, 0.5],
          outline: {
            color: 'red',
            width: 1,
          },
        }
        popupTemplate = {
          title: '房屋编号：{fwbh}',
          content: '地址：{address}  已设置了地势类型',
        }
      }

      // Set symbol and popup
      features.map((feature) => {
        feature.symbol = symbol
        feature.popupTemplate = popupTemplate
        return feature
      })

      view.graphics.addMany(features)
    },
    //获取来的框选房屋进行回显
    getOldSelect() {
      if (this.selectArea.length > 0) {
        this.displayResults2(this.view1, this.selectArea, '2')
      }
    },
    clearMapView() {
      this.selectData = []
      this.selectArea = []
      this.view1.popup.close()
      this.view1.graphics.removeAll()
    },
    submitHouseList() {
      if (!this.warnValue1) {
        this.$message.error('请选择地势类型')
        return
      }
      if (this.selectData.length < 1) {
        this.$message.error('请选择需要提交的房屋')
        return
      }
      console.log(this.selectData)
      this.showInfo = true
      //提交房屋信息
    },
  },
}
</script>

<style>
.mapview-pannel1,
#mapview2 {
  position: absolute;
  width: 100%;
  /* margin-top: 30px; */
  height: 95%;
}

.top {
  background: #fff;
  height: 50px;
  line-height: 50px;
}

.rowclass {
  margin-left: 10px;
  margin-left: 10px;
}
</style>
